import { constantRouterMap } from '@/router'

/**
 * 20180802 递归设置子菜单Component add by jiahikun
 * @param menu
 */
function setMenuComponent(menu) {
   menu.component = () => import('@/views/' + menu.path)
   if(menu.children !== undefined) {
      for (let i = 0; i < menu.children.length; i++) {
        setMenuComponent(menu.children[i])
      }
    }
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { menus } = data
        // 动态加载菜单 20180802 add by jiahaikun

        const componentLayout = 'layout/Layout'
        for (let i = 0; i < menus.length; i++) {
          menus[i].component = () => import('@/views/' + componentLayout)// 直接写字符串'../../views/'，不写会有异常
          for (let j = 0; j < menus[i].children.length; j++) {
            setMenuComponent(menus[i].children[j])
          }
        }
        commit('SET_ROUTERS', menus)
        resolve()
      })
    }
  }
}

export default permission
